package com.nondo.dean.dealer.service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.dean.common.constants.ViewType;
import com.nondo.dean.common.tool.AliyunOssTool;
import com.nondo.dean.common.tool.BeanUtils;
import com.nondo.dean.common.tool.IPUtil;
import com.nondo.dean.common.tool.RequestUtils;
import com.nondo.dean.common.tool.StringUtils;
import com.nondo.dean.dealer.common.Constant;
import com.nondo.dean.dealer.common.DateProcessUtils;
import com.nondo.dean.dealer.domain.Activity;
import com.nondo.dean.dealer.domain.ActivityCount;
import com.nondo.dean.dealer.domain.ActivityExample;
import com.nondo.dean.dealer.domain.ActivityGoods;
import com.nondo.dean.dealer.domain.CustomerView;
import com.nondo.dean.dealer.domain.Store;
import com.nondo.dean.dealer.mapper.ActivityMapper;
import com.nondo.dean.dealer.model.UserBean;
import com.nondo.dean.dealer.model.param.ActivityParam;
import com.nondo.dean.dealer.model.result.ActivityDetailResult;
import com.nondo.dean.dealer.model.result.ActivityProductResult;
import com.nondo.dean.dealer.model.result.ActivityResult;
import com.nondo.dean.dealer.model.result.ProductResult;

/**
 * @author xiaofan
 * @Description: 活动业务管理类
 * @throws
 * @date 2018-05-0910:43
 * @Version 0.1
 */
@Component
public class ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityGoodsService activityGoodsService;
    
    @Autowired
    ProductService productService;
    
    @Autowired
    UserService userService;
    
    @Autowired
    StoreService storeService;

    @Autowired
    private ActivityTemplateService activityTemplateService;

    @Autowired
    private AliyunOssTool aliyunOssTool;
    
    @Autowired
    private ActivityCountService activityCountService;
    
    @Autowired
    private CustomerViewService customerViewService;

    /**
     * 添加活动
     * @param activity
     * @return
     */
    public int add(Activity activity){
        return activityMapper.insertSelective(activity);
    }




    /**
     * 新建app活动
     * @param param
     * @return
     */
    @Transactional
    public Integer addAppActivity(ActivityParam param){
        Integer userId = userService.getLoginUserId();
        Activity activity = new Activity();
        BeanUtils.copy(param,activity);
        activity.setStartTime(DateProcessUtils.getDate(param.getBeginData(),DateProcessUtils.YMDHMS_BREAK));
        activity.setEndTime(DateProcessUtils.getDate(param.getEndData(),DateProcessUtils.YMDHMS_BREAK));
        activity.setUserId(userId);
        activityMapper.insertSelective(activity);
        List<ActivityProductResult> list = param.getProductResultList();
        for(ActivityProductResult result : list){
            ActivityGoods activityGoods = new ActivityGoods();
            activityGoods.setProductId(result.getId());
            activityGoods.setAcitivityId(activity.getId());
            activityGoods.setDiscountRate(param.getDiscountRate());
            activityGoods.setStatus(Constant.COMMODITY_STATUS_START);
            activityGoodsService.add(activityGoods);
        }
        return activity.getId();
    }

    /**
     * app活动管理列表
     * @param offset
     * @param limit
     * @return
     */
    public List<ActivityResult> searchActivityList(int offset,int limit,Activity activity){
        List<ActivityResult> newList =new ArrayList<>();
        ActivityExample example =new ActivityExample();
        RowBounds rowBounds = new RowBounds(offset, limit);
        example.setOrderByClause("start_time DESC");
        setCriteria(activity, example);
        List<Activity> activities = activityMapper.selectByExampleWithRowbounds(example,rowBounds);
        for(Activity beans : activities){
            ActivityResult activityResult = new ActivityResult();
            activityResult=ActivityResult.coverToBean(beans);
            if(beans.getTemplateId() != null){
                activityResult.setTemplateName(activityTemplateService.select(beans.getTemplateId()).getName());
            }
            updateActivityStauts(beans);
            activityResult.setStartTime(DateProcessUtils.formatDate(beans.getStartTime(),"yyyy年MM月dd日"));
            activityResult.setEndTime(DateProcessUtils.formatDate(beans.getEndTime(),"yyyy年MM月dd日"));
            newList.add(activityResult);
        }
        return newList;
    }

    /**
     * 查询分页总数
     * @param activity
     * @return
     */
    public Long count(Activity activity){
        ActivityExample example = new ActivityExample();
        setCriteria(activity, example);
        return activityMapper.countByExample(example);
    }

    /**
     * 设置查询条件
     * @param activity
     * @param example
     */
    private void setCriteria(Activity activity, ActivityExample example) {
        ActivityExample.Criteria criteria = example.createCriteria();
        if (activity.getUserId() != null) {
            criteria.andUserIdEqualTo(activity.getUserId());
        }
        criteria.andDelFlagEqualTo(Activity.DEL_FLAG_NORMAL);
    }

    /**
     * 删除活动
     * @param activity
     * @return
     */
    public Integer update(Activity activity){
        return activityMapper.updateByPrimaryKey(activity);
    }

    /**
     * 按id查询活动
     * @param id
     * @return
     */
    public Activity select(Integer id){
        return activityMapper.selectByPrimaryKey(id);
    }

    /**
     * 按活动名称查询
     * @param name
     * @return
     */
    public Activity selectName(String name){
        ActivityExample example = new ActivityExample();
        example.createCriteria().andNameEqualTo(name).andDelFlagEqualTo(Activity.DEL_FLAG_NORMAL);
        return CollectionUtils.isNotEmpty(activityMapper.selectByExample(example)) ? activityMapper.selectByExample(example).get(0) : null;
    }

    /**
     * app查询活动 和 参与活动的商品
     * @param activityId
     * @return
     */
    public ActivityDetailResult activityDetail(Integer activityId, HttpServletRequest request){
        ActivityDetailResult bean = new ActivityDetailResult();
        Activity activity = select(activityId);
        UserBean user = userService.getUserBeanById(activity.getUserId());
        Store store = storeService.select(user.getStoreId());
        bean.setAddress(store.getAddress());
        bean.setPhone(store.getPhone());
        BeanUtils.copy(activity, bean);
        bean.setTemplateUrl(activityTemplateService.select(activity.getTemplateId()).getTemplateUrl());
        bean.setStartTime(DateProcessUtils.formatDate(activity.getStartTime(),"MM-dd"));
        bean.setEndTime(DateProcessUtils.formatDate(activity.getEndTime(),"MM-dd"));
        
        List<ActivityProductResult> newList= new ArrayList<ActivityProductResult>();
        List<ActivityGoods> activityGoodsList = activityGoodsService.getActivityGoodsList(activityId);
        for(ActivityGoods activityGoods : activityGoodsList){
            ActivityProductResult result = new ActivityProductResult();
            ProductResult productResult = productService.getProductBeanById(activityGoods.getProductId());
            BeanUtils.copy(productResult, result);
            BeanUtils.copy(activityGoods, result);
            result.setId(activityGoods.getProductId());
            result.setMainImage(aliyunOssTool.getImgUrl(productResult.getMainImage()));
            newList.add(result);
        }
        bean.setActivityProductResultList(newList);
        
        // 添加活动浏览记录和活动统计
        CustomerView customerView = new CustomerView();
        customerView.setClient(RequestUtils.getClientInfo(request));
        customerView.setUrl(RequestUtils.getRequestUrl(request));
        customerView.setIp(IPUtil.getIpAddress(request));
        customerView.setType(ViewType.ACTIVITY);
        customerView.setGoValue(String.valueOf(activityId));
        customerView.setDescription("活动名称：" + activity.getName());
        customerViewService.add(customerView);
        
        ActivityCount activityCount = null;
        activityCount = activityCountService.selectByActivityId(activityId);
        if (activityCount == null) {
            activityCount = new ActivityCount();
            activityCount.setActivityId(activityId);
            activityCount.setViewNum(1);
            activityCountService.add(activityCount);
        } else {
            activityCount.setViewNum(activityCount.getViewNum()+1);
            activityCountService.update(activityCount);
        }
        
        return bean;
    }

    /**
     * 列表管理
     * @param offset
     * @param limit
     * @param activity
     * @return
     */
    public List<Activity> list(Integer offset, Integer limit, Activity activity) {
        ActivityExample example = new ActivityExample();
        example.setOrderByClause("create_date DESC");
        ActivityExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, activity);
        RowBounds rowBounds = new RowBounds(offset, limit);
        return activityMapper.selectByExampleWithRowbounds(example, rowBounds);
    }

    /**
     * 设置查询条件
     *
     * @param criteria
     * @param activity
     */
    void setCriteria(ActivityExample.Criteria criteria, Activity activity) {
        if (activity != null) {
            if (activity.getId() != null) {
                criteria.andIdEqualTo(activity.getId());
            }
            if (StringUtils.isNoneBlank(activity.getName())) {
                criteria.andNameEqualTo(activity.getName());
            }
            if(activity.getStartTime() !=null){
                criteria.andStartTimeEqualTo(activity.getStartTime());
            }
        }
        criteria.andDelFlagEqualTo(Activity.DEL_FLAG_NORMAL);
    }

    /**
     * 更新活动状态
     * @return
     */
    public void updateActivityStauts(Activity activity){

                Date date = DateProcessUtils.getDate(DateProcessUtils.getNowDateText(DateProcessUtils.YMDHMS_BREAK),DateProcessUtils.YMDHMS_BREAK);
                //进行中
                if((date.compareTo(activity.getStartTime()) >0 || activity.getStartTime().compareTo(date) == 0) && (date.compareTo(activity.getEndTime())<0 || date.compareTo(activity.getEndTime()) == 0)){
                    ActivityExample activityExamp = new ActivityExample();
                    activityExamp.createCriteria().andIdEqualTo(activity.getId());
                    Activity bean = new Activity();
                    bean.setStatus(Constant.ACTIVITY_STATUS_BEGIN);
                    activityMapper.updateByExampleSelective(bean,activityExamp);
                }
                //已过期
                if(date.compareTo(activity.getEndTime()) > 0){
                    ActivityExample activityExample = new ActivityExample();
                    activityExample.createCriteria().andIdEqualTo(activity.getId());
                    Activity bean = new Activity();
                    bean.setStatus(Constant.ACTIVITY_STATUS_HAVE_EXPIRED);
                    activityMapper.updateByExampleSelective(bean,activityExample);
                }

    }

    /**
     * 预览活动详情
     * @param activityParam
     * @return
     */
    public ActivityDetailResult previewActivityDetail(ActivityParam activityParam) {
        ActivityDetailResult bean = new ActivityDetailResult();
        BeanUtils.copy(activityParam, bean);
        
        if (activityParam.getBeginData() != null) {
            bean.setStartTime(DateProcessUtils.formatDate(DateProcessUtils.getDate(activityParam.getBeginData(), "MM-dd"),"MM-dd"));
        }
        if (activityParam.getEndData() != null) {
            bean.setEndTime(DateProcessUtils.formatDate(DateProcessUtils.getDate(activityParam.getEndData(), "MM-dd"),"MM-dd"));
        }
        bean.setActivityProductResultList(activityParam.getProductResultList());
        
        Integer storeId = userService.queryStoreId();
        Store store = storeService.select(storeId);
        bean.setAddress(store.getAddress());
        bean.setPhone(store.getPhone());
        
        return bean;
    }
}
